package common.proxy;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

@Slf4j
public class HttpUtil {

    /**
     * 转化各个httpclient返回的html
     */
    public static String parsingHtml(CloseableHttpResponse responce) throws Exception {
        String html = null;
        HttpEntity entity = responce.getEntity();
        if (entity != null) {
            html = EntityUtils.toString(entity, "UTF-8");
            html = html.replace("&nbsp;", " ");
        }
        return html;
    }

    //这里的和eventualclient的方法一样
    public static String getHtml(CookieStore cookieStore, String url, String referer) {

        String html = "";

        //CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
                    //.setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce = null;
            try {
                httpget = new HttpGet(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);

                // httpget.setConfig(requestConfig);

                String userAgent = Thread.currentThread().getName();
                httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);
                httpget.addHeader(HttpHeaders.REFERER, referer);
                httpget.addHeader("Connection", "keep-alive");
                httpget.addHeader("Accept-Encoding", "gzip, deflate");
                httpget.addHeader("Accept-Language", "en-US;q=0.5,en;q=0.3");
                httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

                responce = httpClient.execute(httpget);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码

                ////System.out.println("httpclient耗时"
                //+ (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {

                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (responce != null) {
                    try {
                        responce.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }


    public static String getHtmlWhithConfig(BasicCookieStore cookieStore, HttpClientConfig clientConfig) {
        String html = "";
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients
                    .custom()
                    .setDefaultCookieStore(cookieStore)
                    .setDefaultCredentialsProvider(clientConfig.getCredsProvider())
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce = null;
            try {
                httpget = new HttpGet(clientConfig.getUrl());
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);

                httpget.setConfig(requestConfig);

                String userAgent = Thread.currentThread().getName();
                httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);
                httpget.addHeader(HttpHeaders.REFERER, clientConfig.getRefer());
//                httpget.addHeader("Connection", "keep-alive");
//                httpget.addHeader("Accept-Encoding", "gzip, deflate");
//                httpget.addHeader("Accept-Language", "en-US;q=0.5,en;q=0.3");
//                httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

                responce = httpClient.execute(httpget);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码

                ////System.out.println("httpclient耗时"
                //+ (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {

                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (responce != null) {
                    try {
                        responce.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static String postHtml(CookieStore cookieStore, String url, String referer, String args) {

        String html = "";
        CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce = null;
            try {
                httppost = new HttpPost(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);


                httppost.setConfig(requestConfig);

                String userAgent = Thread.currentThread().getName();
                httppost.addHeader(HttpHeaders.USER_AGENT, userAgent);
                httppost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.REFERER, referer);
                httppost.addHeader("Connection", "keep-alive");
                httppost.addHeader("Accept-Encoding", "gzip, deflate");
                httppost.addHeader("Accept-Language", "en-US;q=0.5,en;q=0.3");
                httppost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

                httppost.setEntity(new StringEntity(args));
                // 得到responce对象
                responce = httpClient.execute(httppost);
                // 返回码
                int resStatu = responce.getStatusLine().getStatusCode();

                ////System.out.println("httpclient耗时" //+ (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_MOVED_PERMANENTLY || resStatu == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header header = responce.getFirstHeader("location");
                    String redirectUrl = new URL(new URL(url), header.getValue().replace(" ", "+")).toString();
                    System.out.println("跳转地址" + redirectUrl);
                    html = getHtml(cookieStore, redirectUrl, referer);
                    break;
                } else if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (responce != null) {
                    try {
                        responce.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static String postHtmlQuanWen(CookieStore cookieStore, String url, String referer, String args) {
        //
        String html = "";
        //  CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
                    //.setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce = null;
            try {
                httppost = new HttpPost(url);
                // RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);


                //  httppost.setConfig(requestConfig);

                String userAgent = Thread.currentThread().getName();
                httppost.addHeader(HttpHeaders.USER_AGENT, userAgent);
                httppost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.REFERER, referer);
                httppost.addHeader("Connection", "keep-alive");
                httppost.addHeader("Accept-Encoding", "gzip, deflate");
                httppost.addHeader("Accept-Language", "en-US;q=0.5,en;q=0.3");
                httppost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

                httppost.setEntity(new StringEntity(args));
                // 得到responce对象
                responce = httpClient.execute(httppost);
                // 返回码
                int resStatu = responce.getStatusLine().getStatusCode();

                if (resStatu == HttpStatus.SC_MOVED_PERMANENTLY || resStatu == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header header = responce.getFirstHeader("location");
                    String redirectUrl = new URL(new URL(url), header.getValue().replace(" ", "+")).toString();
                    System.out.println("跳转地址" + redirectUrl);
                    html = getHtml(cookieStore, redirectUrl, referer);
                    break;
                } else if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (responce != null) {
                    try {
                        responce.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static String postJsonHtml(CookieStore cookieStore, String url, String referer, String args) {

        String html = "";
        //CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
                    //.setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(url);
                //RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);

                RequestConfig requestConfig = RequestConfig.custom()
                        //没有链接,没有响应超时断开
                        .setSocketTimeout(60000)
                        //链接后没有响应数据, 超时断开
                        .setConnectTimeout(60000)
                        //.setProxy(new HttpHost(PROXY_STR,PORT_STR))
//				.setRedirectsEnabled(JumpFlag)
                        .build();// 设置请求和传输超时时间

                httppost.setConfig(requestConfig);
                httppost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
                httppost.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36");
                httppost.addHeader(HttpHeaders.REFERER, referer);
                httppost.setEntity(new StringEntity(args));
                responce = httpClient.execute(httppost);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码

                //System.out.println("httpclient耗时"
                //+ (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static Boolean DownPdfWithProxy(CookieStore cookieStore, String url, String referer, String filename) {
        Boolean result = false;


        //CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore)
                    //.setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            int resStatu = 0;
            try {
                while (true) {

                    httpget = new HttpGet(url);
                    //RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);

                    RequestConfig requestConfig = RequestConfig.custom()
                            //没有链接,没有响应超时断开
                            .setSocketTimeout(60000)
                            //链接后没有响应数据, 超时断开
                            .setConnectTimeout(60000)
                            //.setProxy(new HttpHost(PROXY_STR,PORT_STR))
//				.setRedirectsEnabled(JumpFlag)
                            .build();// 设置请求和传输超时时间

                    httpget.setConfig(requestConfig);
                    httpget.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36");
                    httpget.addHeader(HttpHeaders.REFERER, referer);
                    responce = httpClient.execute(httpget);//得到responce对象

                    resStatu = responce.getStatusLine().getStatusCode();//返回码

                    if (resStatu != 301 && resStatu != 302) {
                        break;
                    }
                    url = responce.getHeaders("Location")[0].getValue().replace(" ", "");
                    System.out.println(url);
                }


                //System.out.println("httpclient耗时" //+ (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {//200正常  其他就不对
                    HttpEntity entity = responce.getEntity();   //获得相应实体
                    if (entity != null) {
                        byte[] buffer = EntityUtils.toByteArray(entity);
                        try {
                            File file = new File(filename);
                            File path = new File(file.getParent());
                            if (!path.exists()) {
                                path.mkdirs();
                                log.info("创建了路径?+" + path);
                            }
                            createFile(filename, buffer);
                            result = true;
                            break;
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return result;
    }

    public static void createFile(String path, byte[] content)
            throws IOException {
        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

}
